//
//  ViewController.m
//  SBooks
//
//  Created by shansander on 2016/11/11.
//  Copyright © 2016年 shansander. All rights reserved.
//

#import "ViewController.h"
#import "SDServerViewController.h"

#import "AppCustom.h"

#import "SDContentBaseViewController.h"
#import "SDControllerManager.h"
#import "AppMacro.h"
#import "FilePathCollectionViewCell.h"
#import "SDServerActionView.h"
#import "MyHTTPConnection.h"
#import "CapacityTableViewCell.h"


@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    SDServerActionView * serverActionView;
    NSMutableDictionary * file_size_info;
}

@property (nonatomic, weak) IBOutlet UITableView * theRootListView;

@property (nonatomic, strong) NSMutableArray * theFilePathList;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [AppTheme getBackThemeColor];
    
    self.theRootListView.backgroundView = nil;
    self.theRootListView.backgroundColor = [UIColor clearColor];
    self.theFilePathList = [[NSMutableArray alloc] init];
    file_size_info = [[NSMutableDictionary alloc] init];
    [self registNotification];

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self reloadSavedDirctionPath];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)registNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recevieFilesuccess) name:notification_rected_file_success object:nil];
}

- (void)reloadSavedDirctionPath
{
    
    [self.theFilePathList removeAllObjects];
    NSString * dirctionPath = [AppCustom getSavedFileDirctionPath];
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    NSArray * tmpFileList = [NSArray arrayWithArray:[fileManager contentsOfDirectoryAtPath:dirctionPath error:nil]];
    
    [self.theFilePathList addObjectsFromArray:tmpFileList];
    
    [self.theRootListView reloadData];
    
}
- (void)recevieFilesuccess
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self reloadSavedDirctionPath];
    });
}
- (void)deleteTableCell:(NSIndexPath *)indexPath
{
    NSString * fileName = self.theFilePathList[indexPath.row];
    NSString * dirctionPath = [AppCustom getSavedFileDirctionPath];
    NSString * filePath = [dirctionPath stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        NSError * error;
        [fileManager removeItemAtPath:filePath error:&error];
        if (!error) {
            [self.theFilePathList removeObjectAtIndex:indexPath.row];
            [self.theRootListView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
    
    
}

-(IBAction)onPushServer:(id)sender
{
    
    [[self serverActionView] startAction];
}

- (SDServerActionView * )serverActionView{
    if (!serverActionView) {
        serverActionView = [[SDServerActionView alloc] init];
        [self.view addSubview:serverActionView];
    }
    
    return serverActionView;
}
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.theFilePathList.count != 0) {
        return self.theFilePathList.count + 1;
    }
    return self.theFilePathList.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.theFilePathList.count) {
        CapacityTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"capacitylinecell"];
        [cell displayRamWithFileSizeInfo:file_size_info];
        return cell;
    }else{
        FilePathCollectionViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"filepathcell"];
        NSString * filename = self.theFilePathList[indexPath.row];
        [cell displayCollectionView:filename];
        file_size_info[indexPath] = cell.file_size;
        return cell;
    }
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.theFilePathList.count) {
        
    }else{
        NSString * filePath = self.theFilePathList[indexPath.row];
        NSString * dirctionpath = [AppCustom getSavedFileDirctionPath];
        NSString * path = [dirctionpath stringByAppendingPathComponent:filePath];
        
        __weak ViewController * weak_self = self;
        [AppCustom NSURLSessionGetMiMeTypeWithPath:path andResult:^(id content) {
            NSString * fileType = content;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * controllerIdentifier = [SDControllerManager GetViewControllerByWillShowContentType:fileType];
                SDContentBaseViewController * contentVController = [self.storyboard instantiateViewControllerWithIdentifier:controllerIdentifier];
                contentVController.fileName = filePath;
                [weak_self.navigationController pushViewController:contentVController animated:YES];
            });
        }];

    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.theFilePathList.count) {
        return false;
    }
    return YES;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self deleteTableCell:indexPath];
    }
}

@end
